package com.itheima.reggie.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.constant.CommonConstant;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.service.impl.EmployeeServiceImpl;
import com.itheima.reggie.service.impl.UserServiceImpl;
import com.itheima.reggie.util.IpUtil;
import com.itheima.reggie.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        LoginUserUtil loginUserUtil = InitContext.getInitContext().getApplicationContext().getBean(LoginUserUtil.class);

        HttpServletRequest request = (HttpServletRequest) servletRequest;//向上转型
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String ipAddress = IpUtil.getIpAddress(request);

        //判断放行的接口和静态路径
        if(check(requestURI)){
            toSuccessResponse(request,response,filterChain);
            return;
        }

        //判断后端登录
        if(requestURI.startsWith(CommonConstant.HEADBACKEND)){
            Object backendUser = loginUserUtil.getBackendUser(true, ipAddress, 30L);
            if(backendUser == null){
                //未匹配到放行的接口和静态路径
                toErrorResponse(response);
                return;
            }

            Employee  em = getEmployee(Long.parseLong(backendUser.toString()));

            if(em != null){
                toSuccessResponse(request,response,filterChain);
                return;
            }else{
                //未匹配到放行的接口和静态路径
                toErrorResponse(response);
                return;
            }

        }
        //判断前端登录
        else  if(requestURI.startsWith(CommonConstant.HEADFRONT)){
            Object frontUser = loginUserUtil.getFrontUser(true, ipAddress, 30L);
            if(frontUser == null){
                //未匹配到放行的接口和静态路径
                toErrorResponse(response);
                return;
            }
            User us = getUser(Long.parseLong(frontUser.toString()));
            if(us != null){
                toSuccessResponse(request,response,filterChain);
                return;
            }else{
                //未匹配到放行的接口和静态路径
                toErrorResponse(response);
                return;
            }
        }

        //未匹配到放行的接口和静态路径
        toErrorResponse(response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    //使用上面定义的路径匹配器,进行比对
    private boolean check(String requetURI){
        for (String url : CommonConstant.LOGINURLS) {
            boolean match = PATH_MATCHER.match(url, requetURI);
            if(match){
                return true;//匹配成功就返回true
            }
        }
        return false;//一个也没匹配上,返回false
    }

    private void toErrorResponse(HttpServletResponse response) throws IOException{
        response.getWriter().write(JSON.toJSONString(Result.error(CommonConstant.FILTERERRORMSG)));
    }

    private void toSuccessResponse(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws IOException,ServletException{
        filterChain.doFilter(request,response);//放行
    }

    private Employee getEmployee(Long employee){
        EmployeeService employeeService = InitContext.getInitContext().getApplicationContext().getBean(EmployeeServiceImpl.class);
        LambdaQueryWrapper<Employee> emWrapper = new LambdaQueryWrapper<>();
        emWrapper.eq(employee != null,Employee::getId,employee);
        return employeeService.getOne(emWrapper);
    }

    private User getUser(Long frontuser){
        UserService userService = InitContext.getInitContext().getApplicationContext().getBean(UserServiceImpl.class);
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(frontuser != null, User::getId, frontuser);
        return userService.getOne(userWrapper);
    }
}
